<script setup lang="ts">
//代码高亮引入
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import 'highlight.js/styles/atom-one-dark.css'
import hljs from 'highlight.js'

import {nextTick, onMounted, reactive, ref} from "vue";
import {useRoute} from "vue-router";
import {get_ArticleFind, comment_list,} from "@/api";
import {comment_send, report_handle, send_report_handle} from "@/api/user.ts";
import {Message, Modal} from "view-ui-plus";
import {useStore} from "vuex";
import {usePage} from "@/plugins/pagination.ts";
import Editor from "@/components/Editor.vue";
import reportUpload from "./components/reportUpload.vue"
import html2canvas from "html2canvas";

import UserInfoPoptip from "@/components/UserInfoPoptip.vue";


let pagination = usePage();
const route = useRoute();
const store = useStore();
let USER_INFO = reactive<any>(store.getters.getUserData);
let id = ref<any>(null);
let content = ref();
let detailContent = ref();
let report = ref();
let loading = ref(true);
let hidden = ref(false);
let isAttention = ref(false);// 是否关注用户
let articleObject = ref({
  "id": "",
  "user_id": "",
  "outimg": "",
  "intro": "",
  "name": "",
  "title": "",
  "content": "",
  "username": "",
  "Views": "",
  "tag": "",
  "top": "",
  "create_time": "",
  "update_time": "",
  "delete_time": null,
  "status": null
})
let feedbackValue = ref('');// 反馈文字
let commentList = ref<any>([]);// 评论列表
let replyContent = ref('');// 评论文字
let main_user = ref<any>(null); // 主评论
let next_user = ref<any>(null); // 次评论

let showHandle = ref(false);
let loading_submit = ref(false);
let formElement = ref();
let formHandle = ref<any>({
  anonymity: '',
  content: ''
});
let loading_report = ref(false); // 截图加载


let ruleHandle = ref({
  anonymity: [
    {required: true, message: '请选择是否匿名', trigger: 'blur'}
  ],
  content: [
    {required: true, message: '请输入举报内容', trigger: 'blur'}
  ],
});


const GoAttention = () => {
  // 关注用户
  if (store.getters.loginStatus) {
    // 判断是否登录
    isAttention.value = !isAttention.value
  } else {
    // 未登录
    Message.error('请先登录!')
  }
}

const highlightCode = () => {
  const pre = document.querySelectorAll('pre.ql-syntax');
  //选择所有pre标签并且class为ql-syntax的元素
  pre.forEach((el: any) => {
    hljs.highlightBlock(el);
    // hljs.highlightElement(el);
    //渲染全部指定的标签
  })
}

const heightOverHidden = () => {
  // 高度超出一定后限制高度
  if (content.value.offsetHeight - 1000 > 200) {
    content.value.style.height = '1000px';
    hidden.value = true;
  }
  // console.log([content.value], content.value.offsetHeight)
}

const openContent = () => {
  // 打开隐藏的内容
  hidden.value = false;
  content.value.style.height = 'min-content';
}

const getInfo = () => {
  loading.value = true;
  get_ArticleFind(id.value).then((result: any) => {
    console.log(result)
    if (result.code == 200) {
      articleObject.value = result.data;
      get_comment_list();
      nextTick(() => {
        heightOverHidden();
      })
    } else {
      Message.error('加载失败')
    }
  }).finally(() => loading.value = false)
}

const get_comment_list = () => {
  // 获取文章所有评论
  comment_list({
    n_id: id.value,
    ...pagination
  }).then((result: any) => {
    console.log(result)
    commentList.value = result.data.data;
    nextTick(() => {
      highlightCode()
    })

  })
}

const replyUser = (item: any) => {
  // 回复用户
  commentList.value.forEach((li: any) => {
    li.show = false;
  })
  if (item.show) {
    item.show = false;
    item.placeholder = "";
    main_user.value = null;
    next_user.value = null;
  } else {
    main_user.value = item;
    next_user.value = null;
    item.show = true;
    item.placeholder = `回复 @${item.name}`
  }
}

const replyUserParent = (item: any, li: any) => {
  // 回复用户
  commentList.value.forEach((li: any) => {
    li.show = false;
  })
  item.show = true;
  item.placeholder = `回复 @${li.name}`
  main_user.value = item;
  next_user.value = li;
}

const submit = () => {
  // 发布评论 -> 一级回复
  if (replyContent.value.length < 2) {
    // 字数太少
    return Message.error("多说几个字吧");
  }
  comment_send({
    content: replyContent.value, // 评论内容
    n_id: id.value, // 关联文章ID
  }).then((result: any) => {
    console.log(result)
    if (result.code == 200) {
      get_comment_list();
      Message.success(result.data);
      replyContent.value = "";
    } else if (result.code == 500) {
      Message.error(result.data);
    } else if (result.code == 401) {
      Message.error("请登录后再评论");
    }
  })
}
const submitParent = () => {
  // 发布评论 -> 二级回复
  if (main_user.value.reply.length < 2) {
    // 字数太少
    return Message.error("多说几个字吧");
  }
  console.log(main_user.value, next_user.value)
  let data: any = {
    content: main_user.value.reply, // 评论内容
    n_id: id.value, // 关联文章ID
  }
  if (main_user.value) {
    // 主评论id
    if (main_user.value.user_id == USER_INFO.user_id) {
      return Message.error("不能回复自己的评论")
    }
    data.main_id = main_user.value.id;
  }
  if (next_user.value) {
    // 主评论下回复者ID
    if (next_user.value.user_id == USER_INFO.user_id) {
      return Message.error("不能回复自己的评论")
    }
    data.next_id = next_user.value.user_id;
  }

  comment_send(data).then((result: any) => {
    console.log(result)
    if (result.code == 200) {
      get_comment_list();
      Message.success(result.data);
      main_user.value.reply = "";
    } else if (result.code == 500) {
      Message.error(result.data);
    } else if (result.code == 401) {
      Message.error("请登录后再评论");
    }
  })

}

const handleArticle = () => {
  // 举报
  formHandle.value.n_id = articleObject.value.id;
  formElement.value?.validate((valid) => {
    if (valid) {
      loading_submit.value = true;
      let formData = new FormData();
      let uploadList = report.value.uploadList;
      uploadList.forEach((file: any) => {
        formData.append("file[]", file.file)
      })
      for (let key in formHandle.value) {
        formData.append(key, formHandle.value[key])
      }
      send_report_handle(formData).then((result: any) => {
        console.log(result)
        loading_submit.value = false;
        if (result.code == 200) {
          Message.success(result.data)
          showHandle.value = false;
          formHandle.value = {};
          report.value.handleClear()
        } else {
          Message.error(result.data)
        }
      }).catch((err) => {
        loading_submit.value = false;
      })
    }
  })
}

const takeScreenshot = () => {
  loading_report.value = true;
  html2canvas(detailContent.value,{
    useCORS: true,
    logging: true // 开启调试
  }).then(function (canvas: any) {
    let imgSrc: any = canvas.toDataURL('image/png');
    console.log(imgSrc)
    console.log(report.value)
    report.value.appendChild(imgSrc)
    setTimeout(() => {
      loading_report.value = false;
    }, 500)
  });
}

const openHandle = () => {
  // 判断举报用户是否是作者本人 如果是则拦截本人
  if (articleObject.value.user_id == USER_INFO.user_id) {
    return Message.error("举报自己的文章？？？")
  }
  showHandle.value = true;
}


onMounted(() => {
  console.log(route.params.id)
  id.value = route.params.id;
  getInfo();
})
</script>

<template>
  <div class="detailContent">
    <div class="detailDefault" ref="detailContent">
      <Spin :show="loading" fix></Spin>
      <div class="detailTitle">
        {{ articleObject.title }}
      </div>
      <div class="detailUtil">
        <span>发布日期：{{ articleObject.create_time }}</span>
        <span>浏览量：{{ articleObject.Views }}</span>
        <span>发布人：
          <UserInfoPoptip :articleObject="articleObject">
            <a>{{ articleObject.name }}</a>
          </UserInfoPoptip>
        </span>
      </div>
      <div class="hiddenContentDiv editor ql-container ql-snow" ref="content">
        <div class="hiddenContent" v-if="hidden">
          <a @click="openContent">点击加载更多</a>
        </div>
        <div class="detailText ql-editor" v-code v-if="articleObject.content" v-html="articleObject.content"></div>
      </div>
      <div class="commentDiv">
        <div class="commentTitle">全部评论</div>
        <div class="replyDiv">
          <Editor v-model="replyContent"/>
          <!--          <Input style="width: 100%;" v-model="replyContent" type="textarea" :rows="3" placeholder="我也来说几句"/>-->
          <div class="flex end" style="margin-top: 10px">
            <Button type="primary" @click="submit">发布</Button>
          </div>
        </div>
        <div class="commentList editor ql-container ql-snow">
          <div class="commentItem" v-for="(item,index) in commentList" :key="index">
            <div class="avatar">
              <img :src="item.outimg" alt="">
            </div>
            <div class="content">
              <div class="name">
                <span>{{ item.name }}</span>
                <span v-if="item.user_id == articleObject.user_id" class="tag up">UP</span>
              </div>
              <div class="contentText">
                <div class="commentItemText" v-code v-html="item.content"></div>
                <div class="utils">
                  <span class="createTime">{{ item.create_time }}</span>
                  <span class="reply" @click="replyUser(item)">回复</span>
                </div>
              </div>
              <div class="replyDiv" v-show="item.show">
                <Input style="width: 100%;" v-model="item.reply" type="textarea" :rows="3"
                       :placeholder="item.placeholder || '我也来说几句'"/>
                <div class="flex end" style="margin-top: 10px">
                  <Button type="primary" @click="submitParent">发布</Button>
                </div>
              </div>
              <div class="commentList children">
                <div class="commentItem" v-for="(li,i) in item.children" :key="i">
                  <div class="avatar">
                    <img :src="li.outimg" alt="">
                  </div>
                  <div class="content">
                    <div class="name">
                      <span>{{ li.name }}</span>
                      <span v-if="li.user_id == articleObject.user_id" class="tag up">UP</span>
                      <span v-if="li.next_id" style="margin: 0 10px;color:#999;">回复</span>
                      <a v-if="li.next_id">@{{ li.next_user.name }}</a>
                    </div>
                    <div class="contentText">
                      <div class="commentItemText" v-code v-html="li.content"></div>
                      <div class="utils">
                        <span class="createTime">{{ li.create_time }}</span>
                        <span class="reply" @click="replyUserParent(item,li)">回复</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="detailFloat">
      <div class="headerAuthorInfo">
        <div class="headerAuthor">
          <div class="headerAuthorImg">
            <img :src="articleObject.outimg" alt="">
          </div>
          <div class="headerAuthorName">
            {{ articleObject.name }}
            <div class="intro" v-line-clamp="3" :title="articleObject.intro">{{ articleObject.intro }}</div>
          </div>
        </div>
        <div class="handle">
          <Button type="error" icon="md-sad" style="width: 100%;" ghost @click="openHandle">
            举报文章
          </Button>
        </div>
      </div>


      <div class="scroll">
        <!--        <div class="recommend">-->
        <!--          <div class="recommendTitle">-->
        <!--            推荐-->
        <!--          </div>-->

        <!--        </div>-->
        <div class="feedback">
          <!--          <div class="feedbackTitle">-->
          <!--            反馈-->
          <!--          </div>-->
          <!--          <Input v-model="feedbackValue" maxlength="200" style="margin-top: 5px" show-word-limit type="textarea"-->
          <!--                 :rows="4" placeholder="输入你的建议"/>-->
          <!--          <Button style="margin-top: 5px;" type="delete">提交</Button>-->
        </div>
      </div>
    </div>
  </div>
  <Modal
      loading
      :width="40"
      v-model="showHandle"
      title="举报该文章"
  >
    <div style="position: relative" :class="{pointerNone: loading_submit}">
      <Spin fix v-if="loading_submit"></Spin>
      <Form ref="formElement" :model="formHandle" :rules="ruleHandle" :label-width="100">
        <FormItem label="举报文章" prop="title">
          <a>{{ articleObject.title }}</a>
        </FormItem>
        <FormItem label="是否匿名" prop="anonymity">
          <RadioGroup v-model="formHandle.anonymity">
            <Radio label="0">正常</Radio>
            <Radio label="1">匿名</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="举报内容" prop="content">
          <Input type="textarea" rows="4" v-model="formHandle.content" placeholder="举报内容"></Input>
        </FormItem>
        <FormItem label="截图">
          <reportUpload ref="report"/>
          <Button :loading="loading_report" style="vertical-align: top;margin-left: 10px" @click="takeScreenshot">
            屏幕截图
          </Button>
        </FormItem>
      </Form>
    </div>
    <template #footer>
      <Space :size="20">
        <a @click="showHandle=false">取消</a>
        <Button @click="handleArticle" type="primary" :loading="loading_submit">提交</Button>
      </Space>
    </template>
  </Modal>
</template>

<style lang="scss">

/*pre {
  overflow: auto;
  padding: 4px 8px;
  border-radius: 4px;
}*/

.detailText {
  padding: 15px;
  background-color: #fff;
  overflow: hidden;

  img {
    max-width: 100%;
  }
}

.hiddenContentDiv {
  position: relative;
  box-shadow: 0 5px 10px 0 #eee;

  .hiddenContent {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 5;
    height: 100px;
    background: linear-gradient(transparent 0%, rgba(255, 255, 255, 1) 39%, rgba(255, 255, 255, 1) 100%);;
    color: #333;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
  }
}

.replyDiv {
  .ql-editor {
    border: 1px solid #ccc;
    border-top: none;
    height: 120px;
  }
}


</style>

<style scoped lang="scss">

:deep(.ql-snow .ql-editor pre.ql-syntax) {
  margin: 0;
  padding: 0;
  border-radius: 0;
  white-space: pre;
  background-color: transparent;
}

:deep(.ql-container.ql-snow) {
  border: none;
}

.detailContent {
  width: 950px;
  margin: 30px auto;
  display: flex;

  .detailDefault {
    position: relative;
    width: 670px;
    height: fit-content;
  }

  .detailFloat {
    width: 250px;
    //background-color: #ddd;
    margin-left: 30px;


    .headerAuthorInfo {
      position: sticky;
      z-index: 2;
      top: 115px;
      display: flex;
      flex-direction: column;

      .handle {
        padding: 10px 0;
      }


      .headerAuthor {
        display: flex;
        border-radius: 10px;
        padding: 20px;
        background-color: #83b37f;

        .headerAuthorImg {
          display: flex;
          align-items: center;

          img {
            width: 70px;
            height: 70px;
            border-radius: 50%;
          }
        }

        .headerAuthorName {
          color: white;
          font-size: 20px;
          margin-left: 10px;

          .intro {
            color: white;
            font-size: 14px;

          }
        }
      }
    }

    .scroll {

    }

    .recommend {
      background-color: #fff;
      margin-top: 20px;
      padding: 10px;
      height: 200px;

      .recommendTitle {
        font-size: 16px;
        color: #333;
      }
    }

    .feedback {
      //height: 900px;
      margin-top: 20px;
      position: relative;
      z-index: 1;
    }
  }

  .detailTitle {
    font-size: 28px;
    font-weight: 500;
    padding: 15px;
    background-color: #fff;
    margin-bottom: 5px;
  }

  .detailUtil {
    padding: 15px;
    background-color: #fff;
    margin-bottom: 5px;

    span {
      margin-right: 15px;
    }

  }

  .commentDiv {
    width: 100%;
    margin-top: 15px;
    background-color: #fff;
    box-shadow: 0 0 10px 0 #eee;

    > .replyDiv {
      padding: 15px;
    }

    .commentTitle {
      width: 100%;
      padding: 15px;
      font-size: 16px;
      font-weight: 500;
      border-bottom: 1px solid #ddd;
    }

    .commentList {

      .commentItem {
        display: flex;

        .commentItemText {

          :deep(pre.ql-syntax) {
            white-space: pre;
            margin: 0;
            padding: 0;
          }
        }

        .avatar {
          padding: 15px;

          img {
            width: 60px;
            height: 60px;
            border-radius: 50%;
          }
        }

        .content {
          flex: 1;
          padding: 15px 15px 15px 0;

          .name {
            line-height: 30px;
            padding-bottom: 10px;
            font-size: 14px;
            font-weight: 500;

            .tag {
              padding: 1px 4px;
              border-radius: 3px;
              line-height: 1;
              font-size: 12px;
              margin-left: 10px;

              &.up {
                background-color: #FF6699;
                color: #fff;
              }
            }
          }

          .contentText {
            height: auto;

            .text {
              white-space: pre-line;
              word-break: break-all;
              color: #333;
              padding: 0 !important;
            }

            .utils {
              margin-top: 10px;

              .createTime {
                color: #999;
              }

              .reply {
                color: #999;
                margin-left: 15px;
                cursor: pointer;
                user-select: none;
              }
            }

          }

          .replyDiv {
            margin-top: 10px;
            width: 100%;
          }
        }
      }

      &.children {
        .avatar {
          img {
            width: 30px;
            height: 30px;
          }
        }
      }
    }
  }

}
</style>
